<template>
  <!-- 返回按钮 -->
  <view class="back-btn" @tap="goToLogin">
    <text class="iconfont icon-arrow-left">返回</text>
  </view>
    <view class="dress-detail">
        <!-- 主内容区域 -->
        <scroll-view 
            scroll-y 
            class="content-scroll"
            :scroll-with-animation="true"
            @scroll="handleScroll"
            :enhanced="true"
            :bounces="false"
        >
            <!-- 轮播图区域 -->
            <swiper 
                class="swiper-container" 
                :indicator-dots="true"
                :autoplay="true"
                :interval="3000"
                :duration="500"
                :circular="true"
                indicator-active-color="#e0b080"
                @change="handleSwiperChange"
            >
                <swiper-item 
                    v-for="(img, index) in imageList" 
                    :key="index"
                    @tap="previewImage(index)"
                >
                    <image 
                        :src="img ? url+`${img}` : '/static/tab/logo.png'"
                        mode="aspectFill"
                        class="swiper-image"
                    />
                </swiper-item>
            </swiper>

            <!-- 详情内容区域 -->
            <view class="detail-content">
                <!-- 基本信息卡片 -->
                <view class="info-section elegant-card">
                    <view class="price-row">
                        <view class="price-box">
                            <text class="currency">¥</text>
                            <text class="price">{{detail.price}}</text>
                            <text class="original-price" v-if="detail.originalPrice">¥{{detail.originalPrice}}</text>
                        </view>
                        <button 
                            class="collect-btn" 
                            @tap="toggleCollect"
                            :class="{'collected': isCollected}"
                        >
                            <text class="iconfont icon-heart"></text>
                            <text class="btn-text">{{ isCollected ? '已收藏' : '收藏' }}</text>
                        </button>
                    </view>
                    <view class="title-row">
                        <text class="title">{{detail.name}}</text>
                        <text class="desc">{{detail.desc}}</text>
                    </view>
                    
                    <!-- 标签列表 -->
                    <view class="tags-list" v-if="detail.tags && detail.tags.length">
                        <text 
                            v-for="(tag, index) in detail.tags" 
                            :key="index"
                            class="tag"
                        >{{tag}}</text>
                    </view>
                </view>

                <!-- 评论区域 -->
                <view class="comments-section elegant-card">
                    <view class="section-header">
                        <text class="section-title">用户评价</text>
                        <text class="comment-count">({{comments.length}})</text>
                    </view>
                    
                    <view class="comment-list">
                        <block v-if="comments.length > 0">
                            <view 
                                v-for="(comment, index) in comments" 
                                :key="index"
                                class="comment-item"
                            >
                                <view class="comment-user">
                                    <image 
                                        :src="comment.userInfo?.header ? url+`${comment.userInfo.header}` : '/static/tab/logo.png'"
                                        class="user-avatar"
                                    ></image>
                                    <view class="user-info">
                                        <text class="username">{{comment.userInfo.username}}</text>
                                        <text class="comment-time">{{comment.createTime}}</text>
                                    </view>
                                </view>
                                <view class="comment-content">{{comment.context}}</view>
                            </view>
                        </block>
                        <view v-else class="empty-comment">
                            <text>暂无评价</text>
                        </view>
                    </view>
                </view>

                <!-- 评论输入弹出层 -->
                <view 
                    class="comment-popup" 
                    :class="{'show': showCommentInput}"
                    @touchmove.stop.prevent
                >
                    <view class="comment-mask" @tap="closeCommentInput"></view>
                    <view class="comment-container">
                        <view class="comment-box">
                            <view class="comment-header">
                                <text>写评论</text>
                                <text class="close-btn" @tap="closeCommentInput">×</text>
                            </view>
                            <view class="input-wrapper">
                                <textarea 
                                    v-model="newComment" 
                                    placeholder="写下你的评价..." 
                                    class="comment-textarea"
                                    :adjust-position="false"
                                    :cursor-spacing="20"
                                    :focus="showCommentInput"
                                />
                              <view class="comment-footer">
                                <button
                                    class="submit-btn"
                                    :disabled="!newComment.trim()"
                                    @tap="handleSubmitComment"
                                >
                                  <text>发布</text>
                                </button>
                              </view>
                            </view>

                        </view>
                    </view>
                </view>

                <!-- 套装详情图片展示 -->
                <view class="suit-details" v-if="isSuit">
                    <view class="section-title">套装详情</view>
                    <view class="suit-images">
                        <image 
                            v-for="(img, index) in imageList" 
                            :key="index"
                            :src="url+`${img}`"
                            mode="widthFix"
                            class="detail-image"
                            @tap="previewImage(index)"
                        />
                    </view>
                </view>

                <!-- 底部占位 -->
                <view style="height: 120rpx;"></view>
            </view>
        </scroll-view>

        <!-- 底部按钮 -->
        <view class="bottom-actions">
            <view class="bottom-bar">
                <button class="action-btn comment-btn" @tap="openCommentInput">
                    <text class="iconfont icon-comment"></text>
                    <text>写评论</text>
                </button>
                <button class="action-btn primary-btn" @tap="makeAppointment">
                    <text class="iconfont icon-calendar"></text>
                    <text>立即预约</text>
                </button>
            </view>
        </view>
    </view>
</template>

<script>
import API from '@/api/config.js'

export default {
    data() {
        return {
            url:'http://localhost:8080/download/',
            id: '', // 剧本杀ID
            detail: {},
            comments: [],
            isCollected: false,
            loading: true,
            scrollTop: 0,
            navOpacity: 0,
            currentIndex: 0,
            newComment: '', // 新增评论内容
            showCommentInput: false,
            imageList: [],
            statusBarHeight: 0,
            isSuit: false,
            detailImages: []
        }
    },
    watch: {
        'detail.images': {
            handler(newVal) {
                if (newVal) {
                    this.imageList = newVal.split(',').filter(img => img)
                } else {
                    this.imageList = []
                }
            },
            immediate: true
        }
    },
    methods: {
        // 加载剧本杀详情
        async loadDetail() {
            try {
                uni.showLoading({ title: '加载中...' })
                const res = await uni.request({
                    url: API.GOWN_GET + this.id,
                    method: 'GET'
                })
                
                if (res.data.code === 200) {
                    console.log(res.data.data)
                    this.detail = res.data.data
                    // 加载完详情后检查收藏状态
                    this.checkCollectionStatus()
                } else {
                    console.log(res.data.data)
                    uni.showToast({
                        title: res.data.msg || '加载失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                uni.showToast({
                    title: '加载失败',
                    icon: 'none'
                })
                console.error('加载详情失败:', error)
            } finally {
                uni.hideLoading()
                this.loading = false
            }
        },

        // 加载评论列表
        async loadComments() {
          // debugger
            try {
                const res = await uni.request({
                    url: API.COMMENT_GET + this.id,
                    method: 'GET'
                })
                
                if (res.data.code === 200) {
                    console.log(res.data.data)
                    this.comments = res.data.data
                }
            } catch (error) {
                console.error('加载评论失败:', error)
            }
        },
      goToLogin() {
        uni.navigateBack()
      },

        // 检查收藏状态
        async checkCollectionStatus() {
            try {
                const token = uni.getStorageSync('token')
                if (!token) return
                
                console.log('检查收藏状态，剧本杀ID:', this.id)
                const res = await uni.request({
                    url: API.USER_LIKES,
                    method: 'GET',
                    header: {
                        'Authorization': token
                    }
                })
                
                console.log('获取收藏列表响应:', res)
                
                if (res.data.code === 200) {
                    // 检查当前剧本杀是否在收藏列表中
                    this.isCollected = res.data.data.some(item => item.jbsId === this.id)
                    console.log('当前剧本杀收藏状态:', this.isCollected)
                }
            } catch (error) {
                console.error('检查收藏状态失败:', error)
            }
        },

        // 收藏/取消收藏
        async toggleCollect() {
            const token = uni.getStorageSync('token')
            if (!token) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                })
                return
            }

            try {
                console.log('当前收藏状态:', this.isCollected)
                console.log('剧本杀ID:', this.id)
                
                if (this.isCollected) {
                    // 取消收藏
                    console.log('准备取消收藏，请求URL:', API.USER_LIKE_DELETE + this.id)
                    const res = await uni.request({
                        url: API.USER_LIKE_DELETE + this.id,
                        method: 'POST',
                        header: {
                            'Authorization': token,
                            'Content-Type': 'application/json'
                        }
                    })
                    
                    console.log('取消收藏响应:', res)
                    
                    if (res.data.code === 200) {
                        this.isCollected = false
                        uni.showToast({
                            title: '已取消收藏',
                            icon: 'success'
                        })
                    }
                } else {
                    // 添加收藏
                    console.log('准备添加收藏，请求URL:', API.USER_LIKE_ADD)
                    const res = await uni.request({
                        url: API.USER_LIKE_ADD,
                        method: 'POST',
                        data: {
                            jbsId: this.id
                        },
                        header: {
                            'Authorization': token,
                            'Content-Type': 'application/json'
                        }
                    })
                    
                    console.log('添加收藏响应:', res)
                    
                    if (res.data.code === 200) {
                        this.isCollected = true
                        uni.showToast({
                            title: '收藏成功',
                            icon: 'success'
                        })
                    } else {
                        throw new Error(res.data.message || '收藏失败')
                    }
                }
            } catch (error) {
                console.error('收藏操作失败:', error)
                uni.showToast({
                    title: error.message || '操作失败',
                    icon: 'none'
                })
            }
        },

        // 提交评论
        async submitComment() {
            try {
                // 检查评论内容
                if (!this.newComment.trim()) {
                    uni.showToast({
                        title: '请输入评论内容',
                        icon: 'none'
                    })
                    return
                }
                // 检查登录状态
                const token = uni.getStorageSync('token')
                if (!token) {
                    uni.showToast({
                        title: '请先登录',
                        icon: 'none'
                    })
                    return
                }

                // 显示加载提示
                uni.showLoading({
                    title: '发布中...',
                    mask: true
                })

                const res = await uni.request({
                    url: API.COMMENT_ADD,
                    method: 'POST',
                    header: {
                        'Authorization': token
                    },
                    data: {
                        jbsId: this.id,
                        context: this.newComment.trim(),
                        images: [] // 如果需要上传图片，可以在这里添加
                    }
                })
                
                if (res.data.code === 200) {
                    // 评论成功
                    uni.showToast({
                        title: '评论成功',
                        icon: 'success'
                    })
                    
                    // 清空输入框并关闭
                    this.newComment = ''
                    this.closeCommentInput()
                    
                    // 重新加载评论列表
                    await this.loadComments()
                } else {
                    // 评论失败
                    uni.showToast({
                        title: res.data.msg || '评论失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('提交评论失败:', error)
                uni.showToast({
                    title: '评论失败，请稍后重试',
                    icon: 'none'
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 打开评论输入框
        openCommentInput() {
            const token = uni.getStorageSync('token')
            if (!token) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                })
                return
            }
            
            this.showCommentInput = true
        },

        // 关闭评论输入框
        closeCommentInput() {
            this.showCommentInput = false
            this.newComment = '' // 清空输入内容
        },

        // 处理评论提交按钮点击
        handleSubmitComment() {
            this.submitComment()
        },

        handleScroll(e) {
            const scrollTop = e.detail.scrollTop
            this.scrollTop = scrollTop
            this.navOpacity = Math.min(scrollTop / 300, 1)
        },

        // 处理轮播图切换
        handleSwiperChange(e) {
            this.currentIndex = e.detail.current
        },

        // 切换图片
        switchImage(index) {
            this.currentIndex = index
        },
        
        // 预览图片
        previewImage(current, images) {
            uni.previewImage({
                current: this.url+`${images[current]}`,
                urls: images.map(img => this.url+`${img}`)
            })
        },

        // 添加预约方法
        makeAppointment() {
            const token = uni.getStorageSync('token')
            if (!token) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                })
                return
            }

            const dressInfo = encodeURIComponent(JSON.stringify({
                id: this.detail.id,
                title: this.detail.title,
                description: this.detail.description, // 添加描述信息
                price: this.detail.price,
                images: this.detail.images,
                jbsId:this.id
            }))
            
            uni.navigateTo({
                url: `/pages/reserve/reserve?dress=${dressInfo}`
            })
        },

        goBack() {
            uni.navigateBack()
        }
    },
    onLoad(options) {
        this.url = API.BASE_URL_IMAGE
        this.id = options.id
        // console.log(this.id,'ididididid')
        this.isSuit = options.isSuit === 'true'
        this.loadDetail()
        this.loadComments()
        this.checkCollectionStatus()
        // 获取状态栏高度
        const systemInfo = uni.getSystemInfoSync()
        this.statusBarHeight = systemInfo.statusBarHeight
        
        // 获取详情数据时处理图片
        if (this.detail.images) {
            this.detailImages = this.detail.images.split(',')
        }
    }
}
</script>

<style scoped>
.dress-detail {
    min-height: 100vh;
    background: #000;
    position: relative;
}

.custom-nav {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    height: 44px;
    background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
    backdrop-filter: blur(10px);
}

.nav-back {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 44px;
    width: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-icon {
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
}

.fixed-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: 1;
}

.content-scroll {
    position: relative;
    z-index: 2;
    padding-top: calc(44px + var(--status-bar-height));
    min-height: 100vh;
    box-sizing: border-box;
}

.swiper-container {
    width: 100%;
    height: 100vh;
    position: relative;
}

.swiper-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.thumbnail-scroll,
.thumbnail-container,
.thumbnail-image {
    display: none;
}

.detail-content {
    position: relative;
    margin-top: -60vh;
    padding-top: 40rpx;
    min-height: 100vh;
    background: linear-gradient(
        to bottom,
        transparent,
        rgba(26, 26, 26, 0.8) 100rpx,
        #1a1a1a 300rpx
    );
}

.elegant-card {
    margin: 30rpx;
    padding: 30rpx;
    background: rgba(30, 30, 30, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 20rpx;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.price-box {
    display: flex;
    align-items: baseline;
}

.currency {
    font-size: 32rpx;
    color: #e0b080;
    margin-right: 4rpx;
}

.price {
    font-size: 48rpx;
    color: #e0b080;
    font-weight: 600;
}

.original-price {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.4);
    text-decoration: line-through;
    margin-left: 12rpx;
}

.collect-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12rpx 24rpx;
    border-radius: 32rpx;
    background: rgba(224, 176, 128, 0.1);
    border: 1px solid #e0b080;
    margin: 0;
    min-width: 140rpx;
}

.collect-btn.collected {
    background: #e0b080;
}

.collect-btn .icon-heart {
    font-size: 28rpx;
    margin-right: 8rpx;
    color: #e0b080;
}

.collect-btn.collected .icon-heart {
    color: #ffffff;
}

.collect-btn .btn-text {
    font-size: 24rpx;
    color: #e0b080;
}

.collect-btn.collected .btn-text {
    color: #ffffff;
}

/* 按钮点击效果 */
.collect-btn:active {
    opacity: 0.8;
    transform: scale(0.98);
}

/* 确保按钮在小程序中没有默认样式 */
.collect-btn::after {
    border: none;
}

.title-row {
    margin-bottom: 20rpx;
}

.title {
    font-size: 32rpx;
    color: #ffffff;
    font-weight: 500;
    margin-bottom: 8rpx;
    display: block;
}

.desc {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.6);
    line-height: 1.6;
}

.tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-top: 20rpx;
}

.tag {
    padding: 8rpx 20rpx;
    background: rgba(224, 176, 128, 0.1);
    border: 1px solid rgba(224, 176, 128, 0.2);
    border-radius: 100rpx;
    font-size: 24rpx;
    color: #e0b080;
}

/* 评论区样式 */
.comments-section {
    margin: 30rpx;
}

.section-header {
    display: flex;
    align-items: center;
    padding-bottom: 30rpx;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.section-title {
    font-size: 32rpx;
    color: #ffffff;
    font-weight: 500;
}

.comment-count {
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.5);
    margin-left: 12rpx;
}

.comment-list {
    padding: 20rpx 0;
}

.comment-item {
    padding: 30rpx 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-user {
    display: flex;
    margin-bottom: 16rpx;
}

.user-avatar {
    width: 72rpx;
    height: 72rpx;
    border-radius: 36rpx;
    background: #333;
}

.user-info {
    margin-left: 16rpx;
    display: flex;
    flex-direction: column;
}

.username {
    font-size: 28rpx;
    color: #ffffff;
    margin-bottom: 4rpx;
}

.comment-time {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.4);
}

.comment-content {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
    line-height: 1.6;
    padding-left: 88rpx;
}

.empty-comment {
    padding: 60rpx 0;
    text-align: center;
    color: rgba(255, 255, 255, 0.4);
    font-size: 28rpx;
}

/* 底部按钮样式 */
.bottom-actions {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
}

.bottom-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background: rgba(26, 26, 26, 0.95);
    backdrop-filter: blur(20px);
}

.action-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    font-size: 28rpx;
    font-weight: 500;
}

.comment-btn {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #ffffff;
}

.primary-btn {
    background: linear-gradient(135deg, #e0b080, #d4946f);
    color: #1a1a1a;
}

.action-btn .iconfont {
    font-size: 32rpx;
}

/* 评论输入弹出层 */
.comment-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    pointer-events: none;
}

.comment-popup.show {
    pointer-events: auto;
}

.comment-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    opacity: 0;
    transition: opacity 0.2s ease;
}

.comment-popup.show .comment-mask {
    opacity: 1;
}

.comment-container {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    transform: translateY(100%);
    transition: transform 0.2s ease;
    z-index: 1000;
}

.comment-popup.show .comment-container {
    transform: translateY(0);
}

.comment-box {
    background: #1a1a1a;
    border-radius: 24rpx 24rpx 0 0;
    overflow: hidden;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.3);
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.comment-header text {
    font-size: 32rpx;
    color: #ffffff;
}

.close-btn {
    font-size: 40rpx;
    color: rgba(255, 255, 255, 0.6);
    padding: 10rpx;
}

.input-wrapper {
	width: 80%;
	margin-left: 30rpx;
    padding: 20rpx;
}

.comment-textarea {
    width: 100%;
    height: 200rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 16rpx;
    padding: 20rpx;
    color: #ffffff;
    font-size: 28rpx;
}

.comment-footer {
  height: 100px;
    padding: 0 30rpx 30rpx;
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

.submit-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #e0b080, #d4946f);
    border-radius: 44rpx;
    color: #1a1a1a;
    font-size: 28rpx;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
}

.submit-btn[disabled] {
    opacity: 0.5;
}

/* 轮播图指示点样式 */
:deep(.uni-swiper-dots) {
    bottom: 40rpx;
}

:deep(.uni-swiper-dot) {
    width: 12rpx;
    height: 12rpx;
    border-radius: 6rpx;
    margin: 0 8rpx;
    background: rgba(255, 255, 255, 0.4);
}

:deep(.uni-swiper-dot-active) {
    width: 24rpx;
    background: #e0b080;
}

.suit-details {
    padding: 30rpx;
    background: rgba(255,255,255,0.05);
    margin: 20rpx;
    border-radius: 20rpx;
}

.section-title {
    font-size: 32rpx;
    color: #fff;
    margin-bottom: 20rpx;
    font-weight: 500;
    padding-left: 16rpx;
    border-left: 4rpx solid #e0b080;
}

.suit-images {
    display: flex;
    flex-direction: column;
    gap: 30rpx;
}

.detail-image {
    width: 100%;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.2);
}

.back-btn {
  position: fixed;
  left: 30rpx;
  top: 60rpx;
  z-index: 100;
  width: 72rpx;
  height: 72rpx;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
